//
//  SelfMainViewController.m
//  ArtOfLiving
//
//  Created by 刘虎 on 16/4/29.
//  Copyright © 2016年 刘虎. All rights reserved.
//

#import "SelfMainViewController.h"
#import "ShowViewController.h"
#import "LoginViewController.h"
#import "YiDianIntroduceViewController.h"
#import "FoodMainModel.h"
#import "ZFScanViewController.h"
#import "StatementViewController.h"

@interface SelfMainViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;               //tableView
@property (nonatomic, strong) UIView *headView;                     //头视图
@property (nonatomic, strong) UIImageView *headImageView;           //头视图图片
@property (nonatomic, strong) NSMutableArray *collectionMArr;          //收藏分区下的数组
@property (nonatomic, strong) UIImageView *sectionImageVIew;        //分区头视图
@property (nonatomic, strong) NSMutableArray *otherArr;             //其他cell的数组
@property (nonatomic, strong) UIImageView *userImageView;           //用户头像
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, strong) UIButton *loginBtn;                   //用户登录（注销）按钮
@property (nonatomic, strong) UILabel *userNickNameLabel;           //用户昵称

@end

@implementation SelfMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我";
    [self show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.tabBarController.tabBar.hidden = NO;
    
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];//leancloud查询工具
    //字符串查询
    [query whereKey:@"username" hasPrefix:[AVUser currentUser].username];//根据姓名查询
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        MBProgressHUD *hud = nil;
        for (AVObject *object in objects) {
            
            hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            if ([object[@"username"] isEqualToString:[AVUser currentUser].username]) {
                
                [self.userImageView sd_setImageWithURL:object[@"image"] placeholderImage:[UIImage imageNamed:@"userNoLogin"]];
            }
        }
        [hud hide:YES afterDelay:0.3];
        [self.tableView reloadData];
    }];
}


#pragma mark -----tableView代理-----
//分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 7;
}

//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    if (section == 0) {
        
        return self.isOpen?self.collectionMArr.count:0;
    } else {
        
        return 1;
    }
}

//cell编辑
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        
        cell.textLabel.text = self.collectionMArr[indexPath.row];
    } else {
        
        cell.textLabel.text = self.otherArr[indexPath.section-1];
    }
    
    //判断用户是否登录（注销）
    if ([AVUser currentUser].username == nil) {
        
        [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        self.userNickNameLabel.text = @"用户未登录";
        self.userNickNameLabel.textAlignment = NSTextAlignmentLeft;
        self.loginBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;//左对齐
        self.userImageView.image = [UIImage imageNamed:@"userNoLogin"];//未登录时的图片
    }
    else {
        //        登陆后的设置
        [self.loginBtn setTitle:@"注销" forState:UIControlStateNormal];
        self.userNickNameLabel.text = [NSString stringWithFormat:@"昵称 ： %@",[AVUser currentUser].username];
        self.userNickNameLabel.font = [UIFont systemFontOfSize:22];
        self.userNickNameLabel.textAlignment = NSTextAlignmentCenter;
        self.loginBtn.contentHorizontalAlignment = UIControlContentVerticalAlignmentCenter;
    }
    return cell;
}

//设置分区头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
        self.sectionImageVIew = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 30, 30)];
        if (self.isOpen) {
            
            self.sectionImageVIew.image = [UIImage imageNamed:@"down"];
        } else {
            
            self.sectionImageVIew.image = [UIImage imageNamed:@"right"];
        }
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 100, 30)];
        label.text = @"收藏列表";
        UITapGestureRecognizer *tapSectionGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSectionGesture)];
        [view addGestureRecognizer:tapSectionGesture];
        [view addSubview:self.sectionImageVIew];
        [view addSubview:label];
        return view;
    } else {
    
        return nil;
    }
}


//分区头视图
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 50;
    } else {
        
        return 5;
    }
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    return 50;
}

//cell编辑
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    我的界面的显示界面
    ShowViewController *showVC = [[ShowViewController alloc] init];
    if (indexPath.section == 1) {
//        本地锦囊的下载
        showVC.dataSourceArr = [[DataBaseManager shareDataBaseManager] fetchGuideDataWithTitle:nil downloadURL:nil];
        showVC.registerCELL = @"CollectionGuideCELL";
        showVC.cellName = @"CollectionGuideCell";
        showVC.fromCELL = @"本地锦囊";
        
    } else if (indexPath.section == 0) {
        
        if (indexPath.row == 0) { //视频收藏界面

            showVC.dataSourceArr = [[DataBaseManager shareDataBaseManager] fetchVideoDataWithTitle:nil url:nil descriptions:nil feed:nil];
            showVC.registerCELL = @"CollectionVideoCELL";
            showVC.cellName = @"CollectionVideoCell";
            showVC.fromCELL = @"视频收藏";
        }
        if (indexPath.row == 1) {   //美食收藏界面
            
            showVC.dataSourceArr = [[DataBaseManager shareDataBaseManager] fetchFoodDataWithimageUrl:nil url:nil ID:nil];
            showVC.registerCELL = @"foodMainCELL";
            showVC.cellName = @"FoodMainTableViewCell";
            showVC.fromCELL = @"美食收藏";
        }
    } else if (indexPath.section == 2) {//本地下载视频
        //        查询数据库里是否有内容
        NSArray *tmpArr = [[DataBaseManager shareDataBaseManager] fetchVideoDataWithTitle:nil url:nil descriptions:nil feed:nil];
        NSMutableArray *mArr = [[NSMutableArray alloc] init];
        
        if (tmpArr.count != 0) {  //如果数据库不为空
        
        for (CollectionVideo *model in tmpArr) {
            
            if (![model.url containsString:@"http"]) { //如果包含一个Http的字符串，就将其添加进数组
                
                [mArr addObject:model];
            }
        }
             }
        showVC.dataSourceArr = mArr;
        //        cell的重用
        showVC.registerCELL = @"CollectionVideoCELL";
        showVC.cellName = @"CollectionVideoCell";
        showVC.fromCELL = @"本地视频";
        
    } else if (indexPath.section == 3) {
        //        免责声明
        StatementViewController *sVC = [[StatementViewController alloc]init];
        [self.navigationController pushViewController:sVC animated:YES];
        
    }else if (indexPath.section == 4){
     //   二维码
        ZFScanViewController *zfVC = [[ZFScanViewController alloc] init];
        [self.navigationController pushViewController:zfVC animated:YES];
        
    }
    else if (indexPath.section == 5) {
        //        艺点介绍
        YiDianIntroduceViewController *yiDianIntroduceVC = [[YiDianIntroduceViewController alloc] init];
        [self.navigationController pushViewController:yiDianIntroduceVC animated:YES];
    } else if (indexPath.section == 6) {    //清理缓存
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"艺点~温馨提示" message:@"确定要清除艺点记忆吗😇" preferredStyle:UIAlertControllerStyleAlert];
       
        // 创建清理缓存的提示框
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            // 创建清理缓存的提示框
            MBProgressHUD *hud = [[MBProgressHUD alloc] init];
            [self.view addSubview:hud];
            //加载条上显示文本
            hud.labelText = @"急速清理中";
            //设置对话框
            hud.mode = MBProgressHUDModeDeterminate;
            [hud showAnimated:YES whileExecutingBlock:^{
                
                while (hud.progress < 1.0) {
                    
                    hud.progress += 0.1;
                    [NSThread sleepForTimeInterval:0.2];
                }
                hud.labelText = @"清理完成";
            } completionBlock:^{
          //  删除，出行、美食、视频，数据库中所有的数据
                [[DataBaseManager shareDataBaseManager] deleteGuideDataWithTitle:nil downloadURL:nil];
                [[DataBaseManager shareDataBaseManager] deleteFoodDataWithimageUrl:nil url:nil ID:nil];
                [[DataBaseManager shareDataBaseManager] deleteVideoDataWithTitle:nil url:nil descriptions:nil feed:nil];
            }];
            [self.tableView reloadData];
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:alertAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    if (showVC.registerCELL != nil) {
        
        [self.navigationController pushViewController:showVC animated:YES];
    }
}

#pragma mark - -------收藏列表是否展开的轻拍手势的回调-------
- (void)tapSectionGesture {
    
    self.isOpen = !self.isOpen;
    [self.tableView reloadData];
    
}

#pragma mark - ------滚动视图的代理方法--------
//下拉头视图变大
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset = self.tableView.contentOffset.y;
    //向上偏移量变正  向下偏移量变负
    if (yOffset < -64) {
        CGFloat factor = ABS(yOffset)+180-64;
        CGRect f = CGRectMake(-([[UIScreen mainScreen] bounds].size.width*factor/180-[[UIScreen mainScreen] bounds].size.width)/2,-ABS(yOffset)+64, [[UIScreen mainScreen] bounds].size.width*factor/180, factor);
        self.headImageView.frame = f;
    }else {
        CGRect f = self.headView.frame;
        f.origin.y = 0;
        self.headView.frame = f;
        self.headImageView.frame = CGRectMake(0, f.origin.y, [[UIScreen mainScreen] bounds].size.width, 180);
    }
}

#pragma mark - -------------用户登录相关设置---------
//登录的按钮回调
- (void)loginBtn:(UIButton *)sender {
    
    if ([sender.currentTitle isEqualToString:@"登录"]) {//获得btn的标题
        
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
    else {
        //        创建弹窗
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"艺点~温馨提示" message:@"确定要注销该用户" preferredStyle:UIAlertControllerStyleAlert];
        //        创建按钮1
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        //   调用系统清除用户信息
            [AVUser logOut];
            [self.tableView reloadData];
        }];
        //        创建按钮1
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        //        添加按钮
        [alertController addAction:alertAction];
        [alertController addAction:cancelAction];
        //        退出按钮
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - ----------用户登录头像选择系统相册-----------
//轻拍用户图像手势的回调(选择系统相册)
- (void)tapImageViewGesture {
    
    if ([AVUser currentUser].username == nil) { //如果用户不存在，说明没有登录
        
        [self setAlertControllerWithMessage:@"用户未登录，不可以更换该头像"];
    }else {
        //初始化imagePicker对象
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        //设置相册方式
        [pickerController setSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
        //设置照片可编辑
        pickerController.allowsEditing = YES;
        //设置代理
        pickerController.delegate = self;
        //模态推出相册
        [self presentViewController:pickerController animated:YES completion:^{
            nil;
        }];
    }
}

//选择照片代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    //得到所选取的图片
    UIImage *resultImage = [info objectForKey:UIImagePickerControllerEditedImage];
    //头像获取照片
    self.userImageView.image = resultImage;
    AVUser *user = [AVUser currentUser];
    AVFile *file = [AVFile fileWithName:@"image.png" data:UIImageJPEGRepresentation(resultImage, 2.0)];
    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (succeeded) {
            
            [user setObject:file.url forKey:@"image"];
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
                if (succeeded) {
                    
                    NSLog(@"保存成功");
                }
            }];
        }
    }];
    //回收pickerController
    [picker dismissViewControllerAnimated:YES completion:^{
        nil;
    }];
}

#pragma mark - --------警示框---------
- (void)setAlertControllerWithMessage:(NSString *)message {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"艺点~温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:alertAction];
    [self presentViewController:alertController animated:YES completion:nil];
    NSLog(@"sdgk");
}


#pragma mark - --------显示控件-----------
- (void)show {
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headView;
    [self.headView addSubview:self.headImageView];
    [self.tableView addSubview:self.loginBtn];
    [self.tableView addSubview:self.userNickNameLabel];
    [self.tableView addSubview:self.userImageView];
}


#pragma mark ----------懒加载------------
- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _tableView;
}

//tableView头视图
- (UIView *)headView {
    
    if (!_headView) {
        
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 180)];
    }
    return _headView;
}

//tableView头视图图片
- (UIImageView *)headImageView {
    
    if (!_headImageView) {
        
        _headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 180)];
        _headImageView.image = [UIImage imageNamed:@"yidian4"];
    }
    return _headImageView;
}

//存储收藏分区内容
- (NSMutableArray *)collectionMArr{
    
    if (!_collectionMArr) {
        
        _collectionMArr = [[NSMutableArray alloc] init];
        [_collectionMArr addObject:@"  视频"];
        [_collectionMArr addObject:@"  美食"];
    }
    return _collectionMArr;
}

//存储其他区的内容
- (NSMutableArray *)otherArr {
    
    if (!_otherArr) {
        
        _otherArr = [NSMutableArray arrayWithObjects:@"    本地锦囊", @"    本地视频", @"    免责声明",@"    扫一扫",@"    艺点介绍",@"    清理缓存", nil];
    }
    return _otherArr;
}

//登录注销按钮
- (UIButton *)loginBtn {
    
    if (!_loginBtn) {
        
        _loginBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_loginBtn setFrame:CGRectMake(120, self.headImageView.frame.size.height-50, 200, 50)];
//        _loginBtn.titleLabel.font = [UIFont systemFontOfSize:22];
        [_loginBtn addTarget:self action:@selector(loginBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}

//用户昵称
- (UILabel *)userNickNameLabel {
    
    if (!_userNickNameLabel) {
        
        _userNickNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, self.headImageView.frame.size.height - 100, 200, 50)];
    }
    return _userNickNameLabel;
}

//用户头像
- (UIImageView *)userImageView {
    
    if (!_userImageView) {
        
        _userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, self.headImageView.frame.size.height-100, 100, 100)];
        _userImageView.layer.cornerRadius = 50.f;
        _userImageView.layer.masksToBounds = YES;
        [_userImageView setUserInteractionEnabled:YES];
        _userImageView.layer.borderWidth = 2.0f;
        _userImageView.layer.borderColor = [[UIColor whiteColor] CGColor];
        UITapGestureRecognizer *tapImageView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageViewGesture)];
        [_userImageView addGestureRecognizer:tapImageView];
    }
    return _userImageView;
}
@end
